#include "httppost.h"
#include "ui_httppost.h"

httppost::httppost(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::httppost)
{
    ui->setupUi(this);
}
bool httppost::postMsg(QString url,
                       QMap<QString, QString> headerdata,
                       QByteArray requestData,
                       QByteArray &replyData)
{
    //发送请求的对象
    QNetworkAccessManager manager;
    //请求对象
    QNetworkRequest request;
    request.setUrl(url);

    //设置请求参数
    QMapIterator<QString, QString> it(headerdata);
    while(it.hasNext())
    {
        it.next();
        request.setRawHeader(it.key().toLatin1(),it.value().toLatin1());
    }

    QNetworkReply *reply = manager.post(request, requestData);
    QEventLoop loop;
    //一旦服务器返回，reply会发出信号
    connect(reply, &QNetworkReply::finished, &loop, &QEventLoop::quit);
    loop.exec();
    //死循环，reply发出信号，结束循环

    //判断是否响应成功
    if(reply != nullptr && reply->error() == QNetworkReply::NoError)
    {
        replyData = reply->readAll();
        qDebug() << replyData;
        return true;
    }
    else
    {
        qDebug() << "请求失败";
        return false;
    }
}

httppost::~httppost()
{
    delete ui;
}
